package com.ims.core.doc.service.impl;

import java.math.BigDecimal;
import java.util.*;

import com.baiwang.open.entity.response.ImageInvoicesRecogcollectResponse;
import com.baiwang.open.entity.response.InputComplianceValidateResponse;
import com.baiwang.open.entity.response.node.*;
import com.ims.common.core.domain.model.LoginUser;
import com.ims.common.exception.ServiceException;
import com.ims.common.utils.DateUtils;
import com.ims.common.utils.DictUtils;
import com.ims.common.utils.SecurityUtils;
import com.ims.common.utils.uuid.IdUtils;
import com.ims.core.doc.controller.vo.InvoiceCollectValidateVo;
import com.ims.core.doc.domain.*;
import com.ims.core.doc.service.*;
import com.ims.core.doc.vo.bwapi.InvoiceForRecogcollect;
import com.ims.core.doc.vo.bwapi.InvoiceForValidate;
import com.ims.core.enums.*;
import com.ims.manager.ImsAsyncManager;
import com.ims.manager.factory.ImsAsyncFactory;
import com.ims.util.BaiwangUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.ims.common.utils.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import com.ims.core.doc.mapper.TInCollectMapper;

/**
 * 发票采集Service业务层处理
 *
 * @author IMS
 * @date 2024-07-24
 */
@Service
public class TInCollectServiceImpl implements ITInCollectService
{
    private static final Logger log = LoggerFactory.getLogger(TInCollectServiceImpl.class);

    @Autowired
    private TInCollectMapper tInCollectMapper;

    @Autowired
    private ITInCollectNonInvoiceService tInCollectNonInvoiceService;

    @Autowired
    private ITInCollectInvoiceService tInCollectInvoiceService;

    @Autowired
    private ITInInvoiceService tInInvoiceService;

    @Autowired
    private ITInInvoice51Service tInInvoice51Service;

    @Autowired
    private ITInInvoice61Service tInInvoice61Service;

    @Autowired
    private ITInInvoice83Service tInInvoice83Service;

    @Autowired
    private ITInInvoice84Service tInInvoice84Service;

    @Autowired
    private ITInInvoice11Service tInInvoice11Service;

    @Autowired
    private ITInInvoice14Service tInInvoice14Service;

    @Autowired
    private ITInInvoice15Service tInInvoice15Service;

    @Autowired
    private ITInNonInvoiceService tInNonInvoiceService;

    /**
     * 查询发票采集
     *
     * @param id 发票采集主键
     * @return 发票采集
     */
    @Override
    public TInCollect selectTInCollectById(Long id)
    {
        return tInCollectMapper.selectTInCollectById(id);
    }

    @Override
    public TInCollect selectTInCollectByCollectId(String collectId) {
        return tInCollectMapper.selectTInCollectByCollectId(collectId);
    }

    /**
     * 查询发票采集列表
     *
     * @param tInCollect 发票采集
     * @return 发票采集
     */
    @Override
    public List<TInCollect> selectTInCollectList(TInCollect tInCollect)
    {
        return tInCollectMapper.selectTInCollectList(tInCollect);
    }

    /**
     * 新增发票采集
     *
     * @param tInCollect 发票采集
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int insertTInCollect(TInCollect tInCollect)
    {
        tInCollect.setCollectId(IdUtils.simpleUUID());
        tInCollect.setCreateBy(SecurityUtils.getLoginUser().getUsername());
        tInCollect.setCreateTime(DateUtils.getNowDate());
        int rows = tInCollectMapper.insertTInCollect(tInCollect);
        insertTInCollectEntry(tInCollect);
        return rows;
    }

    /**
     * 修改发票采集
     *
     * @param tInCollect 发票采集
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateTInCollect(TInCollect tInCollect)
    {
        tInCollect.setUpdateTime(DateUtils.getNowDate());
        tInCollectMapper.deleteTInCollectEntryByCollectId(tInCollect.getId());
        insertTInCollectEntry(tInCollect);
        return tInCollectMapper.updateTInCollect(tInCollect);
    }

    /**
     * 批量删除发票采集
     *
     * @param ids 需要删除的发票采集主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteTInCollectByIds(Long[] ids)
    {
        tInCollectMapper.deleteTInCollectEntryByCollectIds(ids);
        return tInCollectMapper.deleteTInCollectByIds(ids);
    }

    /**
     * 删除发票采集信息
     *
     * @param id 发票采集主键
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteTInCollectById(Long id)
    {
        tInCollectMapper.deleteTInCollectEntryByCollectId(id);
        return tInCollectMapper.deleteTInCollectById(id);
    }

    /**
     * 新增发票采集明细信息
     *
     * @param tInCollect 发票采集对象
     */
    public void insertTInCollectEntry(TInCollect tInCollect)
    {
        List<TInCollectEntry> tInCollectEntryList = tInCollect.getTInCollectEntryList();
        String collectId = tInCollect.getCollectId();
        if (StringUtils.isNotNull(tInCollectEntryList))
        {
            List<TInCollectEntry> list = new ArrayList<TInCollectEntry>();
            for (TInCollectEntry tInCollectEntry : tInCollectEntryList)
            {
                tInCollectEntry.setEntryId(IdUtils.simpleUUID());
                tInCollectEntry.setCollectId(collectId);
                tInCollectEntry.setCollectNo(tInCollect.getCollectNo());
                tInCollectEntry.setCustId(tInCollect.getCustId());
                tInCollectEntry.setSiteCode(tInCollect.getSiteCode());
                tInCollectEntry.setSiteName(tInCollect.getSiteName());
                tInCollectEntry.setCreateTime(DateUtils.getNowDate());
                list.add(tInCollectEntry);
            }
            if (list.size() > 0)
            {
                tInCollectMapper.batchTInCollectEntry(list);
            }
        }
    }

    /**
     * 发票采集-识别
     * @param invoiceForRecogcollectList
     */
    @Override
    public void inInvoiceRecogcollectByImport(List<InvoiceForRecogcollect> invoiceForRecogcollectList) {
        // 提交人
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 生成一个 t_in_collect 对象
        TInCollect tInCollect = new TInCollect();
        tInCollect.setCollectNo(IdUtils.getServiceNo("CJ"));
        tInCollect.setSiteCode(loginUser.getSiteCode());
        tInCollect.setSiteName(loginUser.getSiteName());
        tInCollect.setCollectStatus(CollectStatus.WEI_CAI_JI.getCode());
        tInCollect.setCollectStatusName(CollectStatus.WEI_CAI_JI.getName());
        tInCollect.setCollectType(CollectType.SHANG_CHUAN.getCode());
        tInCollect.setCollectTypeName(CollectType.SHANG_CHUAN.getName());
        // 采集数量
        tInCollect.setCollectQty(invoiceForRecogcollectList.size());
        tInCollect.setCreateBy(loginUser.getUsername());
        tInCollect.setCreateTime(DateUtils.getNowDate());
        // 明细
        List<TInCollectEntry> tInCollectEntryList = new ArrayList<>();
        int lineNo = 1;
        for(InvoiceForRecogcollect invoiceForRecogcollect : invoiceForRecogcollectList){
            TInCollectEntry tInCollectEntry = new TInCollectEntry();
            tInCollectEntry.setLineNo(lineNo);
            tInCollectEntry.setCollectNo(tInCollect.getCollectNo());
            tInCollectEntry.setCollectTime(DateUtils.getNowDate());
            tInCollectEntry.setInvoiceUrl(invoiceForRecogcollect.getUlr());
            tInCollectEntry.setEnterStatus(EnterStatus.WEI_RU_CHI.getCode());
            tInCollectEntry.setEnterStatusName(EnterStatus.WEI_RU_CHI.getName());
            tInCollectEntry.setSourceType(CollectType.SHANG_CHUAN.getCode());
            tInCollectEntry.setSourceTypeName(CollectType.SHANG_CHUAN.getName());
            tInCollectEntry.setCreateBy(loginUser.getUsername());
            // 特别记录下文件名称
            tInCollectEntry.getParams().put("fileName", invoiceForRecogcollect.getFileName());
            tInCollectEntryList.add(tInCollectEntry);
            lineNo ++;
        }
        tInCollect.setTInCollectEntryList(tInCollectEntryList);
        // 保存
        int res = this.insertTInCollect(tInCollect);
        // 调用识别接口，返回的明细存为  t_in_collect_invoice & t_in_collect_invoice_entry
        if(res == 1){
            ImageInvoicesRecogcollectResponse response = BaiwangUtils.recogcollect(invoiceForRecogcollectList);
            if(!response.getSuccess()){
                log.error("采集号 {} 识别调用失败 {}, {}", tInCollect.getCollectNo(), response.getErrorResponse().getCode(), response.getErrorResponse().getMessage());
                throw new ServiceException("识别调用失败");
            }
            // 解析正确的返回
            // 识别失败
            int collectFailQty = 0;
            // 重复采集
            int collectRepeatQty = 0;
            // 入池成功
            int collectSuccessQty = 0;
            // 异常发票
            int collectExceptionQty = 0;
            // 查验成功
            int checkSuccessQty = 0;
            // 查验失败
            int checkFailQty = 0;
            // 一个 ImageInvoicesRecogcollect 为一个识别结果
            for(ImageInvoicesRecogcollect imageInvoicesRecogcollect : response.getResponse()){
                // 百望票夹ID
                Long folderId = imageInvoicesRecogcollect.getFolderId();
                // 票夹表
                ImageInvoicesRecogcollectBizInvoiceFolder bizInvoiceFolder = imageInvoicesRecogcollect.getBizInvoiceFolder();
                // 影像文件
                ImageInvoicesRecogcollectMediaFile mediaFile = imageInvoicesRecogcollect.getMediaFile();
                // 查询对应的 tInCollectEntry
                TInCollectEntry inCollectEntry = null;
                for(TInCollectEntry tInCollectEntry : tInCollectEntryList){
                    if(tInCollectEntry.getParams().get("fileName").toString() .equals(mediaFile.getFileName())){
                        inCollectEntry = tInCollectEntry;
                    }
                }
                //
                List<ImageInvoicesRecogcollectMediaInvoice> mediaInvoiceList = imageInvoicesRecogcollect.getMediaInvoiceList();
                // ORC识别状态,默认0 0：未识别，1：识别成功，2:识别失败，3：无法识别
                if(mediaFile.getOcrStatus() != 1){
                    collectFailQty++;
                }
                // 	影像发票对象列表
                for(ImageInvoicesRecogcollectMediaInvoice imageInvoicesRecogcollectMediaInvoice : mediaInvoiceList) {
                    // 识别接口返回的 增值税发票已查验，非增值税发票没有查验，均直接入库，可抵扣标记初始化为 不可抵扣

                    //是否重复识别 TODO 本地进项池判断
//                    if(imageInvoicesRecogcollectMediaInvoice.getRepeatCollect() !=null && imageInvoicesRecogcollectMediaInvoice.getRepeatCollect().equals("1")){
//                        collectRepeatQty ++;
//                    }
                    // 发票状态 0-正常，1-失控， 2-作废，3-红冲，4-异常，7-部分红冲，8-全额红冲 80-红冲发票待确认
                    if(imageInvoicesRecogcollectMediaInvoice.getInvoiceState() !=null && imageInvoicesRecogcollectMediaInvoice.getInvoiceState() == 4){
                        collectExceptionQty ++;
                    }
                    // 查验状态 0：未查验,1：查验通过,2：查验失败,3：查验中
                    if(imageInvoicesRecogcollectMediaInvoice.getInspectionStatus() == 2){
                        checkFailQty ++;
                    }
                    if(imageInvoicesRecogcollectMediaInvoice.getInspectionStatus() == 1){
                        checkSuccessQty ++;
                    }

                    // 判断返回发票的类型，根据此类型生成 t_in_collect_invoice 或者  t_in_collect_non_invoice

                    // Long	4	票据类型：1-增值税发票 2-非增值税发票
                    if (imageInvoicesRecogcollectMediaInvoice.getNoteType().equals(1L)) {
                        // 采集增值税发票
                        TInCollectInvoice tInCollectInvoice = new TInCollectInvoice();
                        tInCollectInvoice.setCustId(tInCollect.getCustId());
                        tInCollectInvoice.setSiteCode(tInCollect.getSiteCode());
                        tInCollectInvoice.setSiteName(tInCollect.getSiteName());
                        tInCollectInvoice.setCollectId(tInCollect.getCollectId());
                        tInCollectInvoice.setCollectNo(tInCollect.getCollectNo());
                        tInCollectInvoice.setCollectStatus(CollectStatus.YI_CAI_JI.getCode());
                        tInCollectInvoice.setCollectStatusName(CollectStatus.YI_CAI_JI.getName());
                        // 发票号码
                        tInCollectInvoice.setInvoiceNo(imageInvoicesRecogcollectMediaInvoice.getInvoiceNo());
                        // 发票代码
                        tInCollectInvoice.setInvoiceCode(imageInvoicesRecogcollectMediaInvoice.getInvoiceCode());
                        // 开票日期：YYYY-MM-DD
                        tInCollectInvoice.setInvoiceDate(imageInvoicesRecogcollectMediaInvoice.getInvoiceDate());
                        // 发票类型：
//                        99 其他发票
//                        01 增值税专用发票
//                        03 机动车销售统一发票
//                        04 增值税普通发票
//                        08 增值税电子专用发票
//                        10 增值税电子普通发票
//                        11 增值税普通发票(卷式)
//                        14 增值税电子普通发票(通行费)
//                        15 二手车销售统一发票
//                        31 数电发票（增值税专用发票）
//                        32 数电发票（增值税普通发票）
//                        1002 火车票
//                        1003 航空电子客票行程单
//                        1004 出租车发票
//                        1005 通用定额发票
//                        1006公路水路客运发票
//                        1007 通用机打发票
//                        1008 过路费发票
//                        1009区块链电子发票
//                        1010 火车票退票费
//                        1011 医疗电子票据（住院）
//                        1012 医疗电子票据（门诊）
//                        1013 通用（电子）发票
//                        51 数电发票（铁路电子客票）
//                        61 数电发票（航空运输电子客票行程单）
//                        83 电子发票（机动车销售统一发票）
//                        84 电子发票（二手车销售统一发票）
//                        85 数电纸质发票（增值税专用发票）
//                        86 数电纸质发票（增值税普通发票）
//                        1015 海关缴款书
//                        1016 航空运输电子客票行程单退改费
                        tInCollectInvoice.setInvoiceType(imageInvoicesRecogcollectMediaInvoice.getInvoiceType());
                        tInCollectInvoice.setInvoiceTypeName(DictUtils.getDictLabel("in_invoice_type", imageInvoicesRecogcollectMediaInvoice.getInvoiceType()));

                        // 合计金额,火车票金额，飞机票价
                        tInCollectInvoice.setFeeWithoutTax(imageInvoicesRecogcollectMediaInvoice.getTotalAmount());
                        // 	合计税额：1.增值税专/普/电票：税额合计；2.机动车：增值税税额；3.1003-航空电子行程单和1016-航空运输电子客票行程单退票费：燃油附加费 ；5.51-数电票（铁路电子客票）：税额；6.61-数电票（航空电子客票行程单）：增值税税额；
                        tInCollectInvoice.setTax(imageInvoicesRecogcollectMediaInvoice.getTotalTax());
                        // 价税合计，飞机合计金额，火车等总金额
                        tInCollectInvoice.setFee(imageInvoicesRecogcollectMediaInvoice.getAmountTax());

                        // 销方名称
                        tInCollectInvoice.setSellerName(imageInvoicesRecogcollectMediaInvoice.getSaleName());
                        // 销方税号
                        tInCollectInvoice.setSellerNumber(imageInvoicesRecogcollectMediaInvoice.getSaleTaxNo());
                        // 销方地址电话
                        tInCollectInvoice.setSellerAddress(imageInvoicesRecogcollectMediaInvoice.getSaleAddressPhone());
                        // 销方开户行账户
                        tInCollectInvoice.setSellerBank(imageInvoicesRecogcollectMediaInvoice.getSaleBank());

                        // 购方名称
                        tInCollectInvoice.setBuyerName(imageInvoicesRecogcollectMediaInvoice.getPurchaserName());
                        // 购方税号
                        tInCollectInvoice.setBuyerNumber(imageInvoicesRecogcollectMediaInvoice.getPurchaserTaxNo());
                        // 购方开户行账户
                        tInCollectInvoice.setBuyerBank(imageInvoicesRecogcollectMediaInvoice.getPurchaserBank());
                        // 购方开户行账户
                        tInCollectInvoice.setBuyerAddress(imageInvoicesRecogcollectMediaInvoice.getPurchaserAddressPhone());

                        // 发票状态 0-正常，1-失控， 2-作废，3-红冲，4-异常，7-部分红冲，8-全额红冲 80-红冲发票待确认
                        if(imageInvoicesRecogcollectMediaInvoice.getInvoiceState() != null){
                            tInCollectInvoice.setInvoiceStatus(imageInvoicesRecogcollectMediaInvoice.getInvoiceState());
                            tInCollectInvoice.setInvoiceStatusName(DictUtils.getDictLabel("invoice_status", imageInvoicesRecogcollectMediaInvoice.getInvoiceState()+""));
                        } else {
                            tInCollectInvoice.setInvoiceStatus(InvoiceStatus.NORMAL.getCode());
                            tInCollectInvoice.setInvoiceStatusName(InvoiceStatus.NORMAL.getName());
                        }

                        //发票校验状态，0：未校验，1：校验通过:，2：校验失败
                        tInCollectInvoice.setCheckStatus(imageInvoicesRecogcollectMediaInvoice.getVerifyStatus());
                        tInCollectInvoice.setCheckStatusName(DictUtils.getDictLabel("check_status", imageInvoicesRecogcollectMediaInvoice.getVerifyStatus()+""));

                        // 红蓝发票，0：红票，1：蓝票
                        tInCollectInvoice.setInvoiceFlag(imageInvoicesRecogcollectMediaInvoice.getIsRed());

                        // 	发票签收状态 0-未签收 1-已签收
                        tInCollectInvoice.setSignStatus(imageInvoicesRecogcollectMediaInvoice.getSignStatus()+"");
                        tInCollectInvoice.setSignStatusName(DictUtils.getDictLabel("sign_status", imageInvoicesRecogcollectMediaInvoice.getSignStatus()+""));

                        // 校验码
                        tInCollectInvoice.setCheckCode(imageInvoicesRecogcollectMediaInvoice.getCheckCode());
                        // 备注
                        tInCollectInvoice.setInvoiceRemark(imageInvoicesRecogcollectMediaInvoice.getRemark());
                        // 完税凭证号码
                        tInCollectInvoice.setVoucherNumber(imageInvoicesRecogcollectMediaInvoice.getPaymentVoucherNo());

                        // 发票明细
                        List<TInCollectInvoiceEntry> tInCollectInvoiceEntryList = new ArrayList<>();
                        for ( ImageInvoicesRecogcollectBizInvoiceDetail imageInvoicesRecogcollectBizInvoiceDetail : imageInvoicesRecogcollectMediaInvoice.getInvoiceDetailList()) {
                            TInCollectInvoiceEntry inCollectInvoiceEntry = new TInCollectInvoiceEntry();
                            // 商品编码
                            inCollectInvoiceEntry.setProductCode(imageInvoicesRecogcollectBizInvoiceDetail.getCommodityCode());
                            // 货物或应税劳务名称、项目
                            inCollectInvoiceEntry.setProductName(imageInvoicesRecogcollectBizInvoiceDetail.getCommodityName());
                            // 规格型号
                            inCollectInvoiceEntry.setSpecificatCode(imageInvoicesRecogcollectBizInvoiceDetail.getSpecificationModel());
                            // 单位
                            inCollectInvoiceEntry.setUnit(imageInvoicesRecogcollectBizInvoiceDetail.getUnit());
                            // 数量
                            inCollectInvoiceEntry.setQty(imageInvoicesRecogcollectBizInvoiceDetail.getQuantity());
                            // 单价
                            inCollectInvoiceEntry.setPrice(imageInvoicesRecogcollectBizInvoiceDetail.getUnitPrice());
                            // 总额
                            inCollectInvoiceEntry.setAmount(imageInvoicesRecogcollectBizInvoiceDetail.getAmount());
                            // 税率
                            inCollectInvoiceEntry.setTaxRate(imageInvoicesRecogcollectBizInvoiceDetail.getTaxRate());
                            // 税额
                            inCollectInvoiceEntry.setTax(imageInvoicesRecogcollectBizInvoiceDetail.getTax());
                            tInCollectInvoiceEntryList.add(inCollectInvoiceEntry);
                        }
                        tInCollectInvoice.setTInCollectInvoiceEntryList(tInCollectInvoiceEntryList);

                        // 采集明细更新
                        inCollectEntry.setCheckStatusName(tInCollectInvoice.getCheckStatusName());
                        inCollectEntry.setInvoiceDate(tInCollectInvoice.getInvoiceDate());
                        inCollectEntry.setInvoiceNo(tInCollectInvoice.getInvoiceNo());
                        inCollectEntry.setInvoiceCode(tInCollectInvoice.getInvoiceCode());
                        inCollectEntry.setFeeWithoutTax(tInCollectInvoice.getFeeWithoutTax());
                        inCollectEntry.setFee(tInCollectInvoice.getFee());
                        inCollectEntry.setTax(tInCollectInvoice.getTax());
                        inCollectEntry.setInvoiceType(tInCollectInvoice.getInvoiceType());
                        inCollectEntry.setInvoiceTypeName(tInCollectInvoice.getInvoiceTypeName());

                        if(tInCollectInvoiceService.insertTInCollectInvoice(tInCollectInvoice) != 1){
                            log.error("采集 {} 采集增值税发票 {} 保存失败", tInCollectInvoice.getCollectNo(), tInCollectInvoice.getInvoiceNo());
                            // 入池失败
                            inCollectEntry.setEnterStatus(EnterStatus.RU_CHI_SHI_BAI.getCode());
                            inCollectEntry.setEnterStatusName(EnterStatus.RU_CHI_SHI_BAI.getName());

                        } else {
                            // 保存成功后，直接生成正式的发票对象 t_in_invoice 保存到进项池中
                            if(checkInInvoicePool(imageInvoicesRecogcollectMediaInvoice, tInCollectInvoice) == 1){
                                collectSuccessQty ++;
                                // 入池成功
                                inCollectEntry.setEnterStatus(EnterStatus.RU_CHI_CHENG_GONG.getCode());
                                inCollectEntry.setEnterStatusName(EnterStatus.RU_CHI_CHENG_GONG.getName());
                            } else {
                                // 入池失败
                                inCollectEntry.setEnterStatus(EnterStatus.RU_CHI_SHI_BAI.getCode());
                                inCollectEntry.setEnterStatusName(EnterStatus.RU_CHI_SHI_BAI.getName());
                                log.error("采集 {} 增值税发票 {} 保存失败", tInCollectInvoice.getCollectNo(), tInCollectInvoice.getInvoiceNo());
                            }
                        }
                        inCollectEntry.setUpdateTime(DateUtils.getNowDate());
                        tInCollectMapper.updateTInCollectEntry(inCollectEntry);
                    } else {
                        //2-非增值税发票
                        // 采集非增值税发票
                        TInCollectNonInvoice tInCollectNonInvoice = new TInCollectNonInvoice();
                        BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInCollectNonInvoice);
                        tInCollectNonInvoice.setId(null);
                        tInCollectNonInvoice.setCustId(tInCollect.getCustId());
                        tInCollectNonInvoice.setSiteCode(tInCollect.getSiteCode());
                        tInCollectNonInvoice.setSiteName(tInCollect.getSiteName());
                        tInCollectNonInvoice.setCollectId(tInCollect.getCollectId());
                        tInCollectNonInvoice.setCollectNo(tInCollect.getCollectNo());
                        tInCollectNonInvoice.setInvoiceTypeName(DictUtils.getDictLabel("non_invoice_type", imageInvoicesRecogcollectMediaInvoice.getInvoiceType()));
                        tInCollectNonInvoice.setHasPictureName(DictUtils.getDictLabel("has_picture", imageInvoicesRecogcollectMediaInvoice.getHasPicture()+""));

                        tInCollectNonInvoice.setInspectionStatus(0);
                        tInCollectNonInvoice.setInspectionStatusName("暂不支持查验");

                        tInCollectNonInvoice.setIsComplianceCollectName((DictUtils.getDictLabel("is_compliance_collect", imageInvoicesRecogcollectMediaInvoice.getIsComplianceCollect()+"")));
                        tInCollectNonInvoice.setVerifyStatusName((DictUtils.getDictLabel("verify_status", imageInvoicesRecogcollectMediaInvoice.getVerifyStatus()+"")));
                        tInCollectNonInvoice.setIsRedName((DictUtils.getDictLabel("is_red", imageInvoicesRecogcollectMediaInvoice.getIsRed()+"")));
                        tInCollectNonInvoice.setSignStatusName((DictUtils.getDictLabel("sign_status", imageInvoicesRecogcollectMediaInvoice.getSignStatus()+"")));
                        // 发票状态 0-正常，1-失控， 2-作废，3-红冲，4-异常，7-部分红冲，8-全额红冲 80-红冲发票待确认
                        if(imageInvoicesRecogcollectMediaInvoice.getInvoiceState() != null){
                            tInCollectNonInvoice.setInvoiceState(imageInvoicesRecogcollectMediaInvoice.getInvoiceState());
                            tInCollectNonInvoice.setInvoiceStateName(DictUtils.getDictLabel("invoice_status", imageInvoicesRecogcollectMediaInvoice.getInvoiceState()+""));
                        } else {
                            tInCollectNonInvoice.setInvoiceState(InvoiceStatus.NORMAL.getCode());
                            tInCollectNonInvoice.setInvoiceStateName(InvoiceStatus.NORMAL.getName());
                        }
                        // 文件地址
                        tInCollectNonInvoice.setFileAddress(mediaFile.getFileAddress());
                        // 源文件地址
                        tInCollectNonInvoice.setOriginalAddress(mediaFile.getOriginalAddress());
                        // 旋转前文件地址
                        tInCollectNonInvoice.setFileAddressBeforeRotate(mediaFile.getFileAddressBeforeRotate());
                        // 票据类型
                        tInCollectNonInvoice.setNoteType(imageInvoicesRecogcollectMediaInvoice.getNoteType()+"");

                        // 采集明细更新
                        inCollectEntry.setCheckStatusName("暂不支持查验");
                        inCollectEntry.setInvoiceDate(tInCollectNonInvoice.getInvoiceDate());
                        inCollectEntry.setInvoiceNo(tInCollectNonInvoice.getInvoiceNo());
                        inCollectEntry.setInvoiceCode(tInCollectNonInvoice.getInvoiceCode());
                        inCollectEntry.setFeeWithoutTax(tInCollectNonInvoice.getTotalAmount());
                        inCollectEntry.setFee(tInCollectNonInvoice.getAmountTax());
                        inCollectEntry.setTax(tInCollectNonInvoice.getTotalTax());
                        inCollectEntry.setInvoiceType(tInCollectNonInvoice.getInvoiceType());
                        inCollectEntry.setInvoiceTypeName(tInCollectNonInvoice.getInvoiceTypeName());

                        if(tInCollectNonInvoiceService.insertTInCollectNonInvoice(tInCollectNonInvoice) != 1){
                            log.error("采集 {} 采集非增值税发票 {} 保存失败", tInCollectNonInvoice.getCollectNo(), tInCollectNonInvoice.getInvoiceNo());
                            // 入池失败
                            inCollectEntry.setEnterStatus(EnterStatus.RU_CHI_SHI_BAI.getCode());
                            inCollectEntry.setEnterStatusName(EnterStatus.RU_CHI_SHI_BAI.getName());
                        } else {
                            // 保存成功后，直接生成正式的发票各对象 t_in_non_xx 保存到进项池中
                            if(checkInNonInvoicePool(imageInvoicesRecogcollectMediaInvoice, tInCollectNonInvoice) == 1){
                                collectSuccessQty ++;
                                // 入池成功
                                inCollectEntry.setEnterStatus(EnterStatus.RU_CHI_CHENG_GONG.getCode());
                                inCollectEntry.setEnterStatusName(EnterStatus.RU_CHI_CHENG_GONG.getName());
                            } else {
                                log.error("采集 {} 非增值税发票 {} 保存失败", tInCollectNonInvoice.getCollectNo(), tInCollectNonInvoice.getInvoiceNo());
                                // 入池失败
                                inCollectEntry.setEnterStatus(EnterStatus.RU_CHI_SHI_BAI.getCode());
                                inCollectEntry.setEnterStatusName(EnterStatus.RU_CHI_SHI_BAI.getName());
                            }
                        }
                        inCollectEntry.setUpdateTime(DateUtils.getNowDate());
                        tInCollectMapper.updateTInCollectEntry(inCollectEntry);
                    }
                }
            }

            // 更新各数量字段
            tInCollect.setCollectFail(collectFailQty);
            tInCollect.setCollectRepeat(collectRepeatQty);
            tInCollect.setCollectSuccess(collectSuccessQty);
            tInCollect.setCollectException(collectExceptionQty);
            tInCollect.setCollectSuccess(checkSuccessQty);
            tInCollect.setCheckFail(checkFailQty);
            tInCollect.setCollectStatus(CollectStatus.YI_WAN_CHENG.getCode());
            tInCollect.setCollectStatusName(CollectStatus.YI_WAN_CHENG.getName());
            tInCollectMapper.updateTInCollect(tInCollect);
        }
    }

    /**
     * 发票采集-查验方式
     * @param invoiceCollectExcelVoList
     */
    @Override
    public void inInvoiceRecogcollectByValidate(List<InvoiceCollectValidateVo> invoiceCollectExcelVoList, CollectType collectType) {
        // 提交人
        LoginUser loginUser = SecurityUtils.getLoginUser();
        // 生成一个 t_in_collect 对象
        TInCollect tInCollect = new TInCollect();
        tInCollect.setCollectNo(IdUtils.getServiceNo("CJ"));
        tInCollect.setSiteCode(loginUser.getSiteCode());
        tInCollect.setSiteName(loginUser.getSiteName());
        tInCollect.setCollectStatus(CollectStatus.WEI_CAI_JI.getCode());
        tInCollect.setCollectStatusName(CollectStatus.WEI_CAI_JI.getName());
        tInCollect.setCollectType(collectType.getCode());
        tInCollect.setCollectTypeName(collectType.getName());
        // 采集数量
        tInCollect.setCollectQty(invoiceCollectExcelVoList.size());
        tInCollect.setCreateBy(loginUser.getUsername());
        tInCollect.setCreateTime(DateUtils.getNowDate());
        // 明细
        List<InvoiceForValidate> invoiceForValidateList = new ArrayList<>();
        List<TInCollectEntry> tInCollectEntryList = new ArrayList<>();
        int lineNo = 1;
        for(InvoiceCollectValidateVo invoiceCollectExcelVo : invoiceCollectExcelVoList){
            TInCollectEntry tInCollectEntry = new TInCollectEntry();
            tInCollectEntry.setLineNo(lineNo);
            tInCollectEntry.setInvoiceNo(invoiceCollectExcelVo.getInvoiceNumber());
            tInCollectEntry.setInvoiceDate(invoiceCollectExcelVo.getBillingDate());
            tInCollectEntry.setInvoiceCode(invoiceCollectExcelVo.getInvoiceCode());
            tInCollectEntry.setCollectNo(tInCollect.getCollectNo());
            tInCollectEntry.setCollectTime(DateUtils.getNowDate());
            // tInCollectEntry.setInvoiceUrl(invoiceForRecogcollect.getUlr());
            tInCollectEntry.setEnterStatus(EnterStatus.WEI_RU_CHI.getCode());
            tInCollectEntry.setEnterStatusName(EnterStatus.WEI_RU_CHI.getName());
            tInCollectEntry.setSourceType(CollectType.DAO_RU.getCode());
            tInCollectEntry.setSourceTypeName(CollectType.DAO_RU.getName());
            tInCollectEntry.setCreateBy(loginUser.getUsername());
            tInCollectEntryList.add(tInCollectEntry);

            // 接口请求对象
            InvoiceForValidate invoiceForValidate = new InvoiceForValidate();
            BeanUtils.copyProperties(invoiceCollectExcelVo, invoiceForValidate);
            invoiceForValidate.setLineNo(lineNo);
            invoiceForValidateList.add(invoiceForValidate);

            lineNo++;
        }
        tInCollect.setTInCollectEntryList(tInCollectEntryList);
        // 保存
        int res = this.insertTInCollect(tInCollect);
        // 另起线程调用百望接口
        if(res == 1){
            ImsAsyncManager.me().execute(ImsAsyncFactory.invoiceValidateFromBaiwang(tInCollect.getCollectId(), invoiceForValidateList));
        }
    }

    /**
     * 采集单调用查验发票
     * @param collectId    采集单ID
     * @param invoiceForValidateList 采集
     */
    @Override
    public void invoiceValidate(String collectId, List<InvoiceForValidate> invoiceForValidateList){
        TInCollect tInCollect = selectTInCollectByCollectId(collectId);
        tInCollect.setCollectStatus(CollectStatus.CAI_JI_ZHONG.getCode());
        tInCollect.setCollectStatusName(CollectStatus.CAI_JI_ZHONG.getName());
        tInCollect.setUpdateTime(DateUtils.getNowDate());
        tInCollectMapper.updateTInCollect(tInCollect);

        // 识别失败
        int collectFailQty = 0;
        // 重复采集
        int collectRepeatQty = 0;
        // 入池成功
        int collectSuccessQty = 0;
        // 异常发票
        int collectExceptionQty = 0;
        // 查验成功
        int checkSuccessQty = 0;
        // 查验失败
        int checkFailQty = 0;

        for(InvoiceForValidate invoiceForValidate : invoiceForValidateList){
            // 修改 t_in_collect_entry
            Map params = new HashMap<>();
            params.put("collectId", collectId);
            params.put("lineNo", invoiceForValidate.getLineNo());
            TInCollectEntry inCollectEntry = tInCollectMapper.getTInCollectEntryByCollectIdAndLineNo(params);

            InputComplianceValidateResponse response = BaiwangUtils.validate(invoiceForValidate);
            //
            if(!response.getSuccess()){
                collectFailQty ++;
                checkFailQty ++;
                log.error("采集号 {} 中发票 {} 查验失败 {}, {}", tInCollect.getCollectNo(), invoiceForValidate.getInvoiceNumber(), response.getErrorResponse().getCode(), response.getErrorResponse().getMessage());
                if(inCollectEntry != null){
                    inCollectEntry.setCheckStatusName(CheckStatus.JIAN_YAN_YI_CHANG.getName());
                    inCollectEntry.setEnterStatus(EnterStatus.WEI_RU_CHI.getCode());
                    inCollectEntry.setEnterStatusName(EnterStatus.WEI_RU_CHI.getName());
                    inCollectEntry.setCollectTime(DateUtils.getNowDate());
                    inCollectEntry.setUpdateTime(DateUtils.getNowDate());
                }
            } else {
                // 解析返回
                InputComplianceValidate inputComplianceValidate = response.getResponse();
                // 发票类型 即查验接口不返回非增值税发票
                // 01:增值税专用发票 -增
                // 03:机动车销售统一发票 -增
                // 04:增值税普通发票 -增
                // 08:增值税电子专用发票 -增
                // 10:增值税电子普通发票 -增
                // 11:增值税普通发票(卷式) -增
                // 14:道路通行费电子普通发票 -增
                // 15:二手车销售统一发票 -增
                // 31:数电票（增值税专用发票） -增
                // 32:数电票（普通发票） -非增
                // 51:数电票（铁路电子客票） -增
                // 61:数电票（航空运输电子客票行程单） -增
                // 85:数电纸质发票（增值税专用发票） -增
                // 86:数电纸质发票（普通发票） -增
                String invoiceType = inputComplianceValidate.getInvoiceType();
                // 发票数据
                InputComplianceValidateFullInvoiceInfo inputComplianceValidateFullInvoiceInfo = inputComplianceValidate.getData();

                // 保存 t_in_collect_invoice
                // 采集增值税发票
                TInCollectInvoice tInCollectInvoice = new TInCollectInvoice();
                tInCollectInvoice.setCustId(tInCollect.getCustId());
                tInCollectInvoice.setSiteCode(tInCollect.getSiteCode());
                tInCollectInvoice.setSiteName(tInCollect.getSiteName());
                tInCollectInvoice.setCollectId(tInCollect.getCollectId());
                tInCollectInvoice.setCollectNo(tInCollect.getCollectNo());
                tInCollectInvoice.setCollectStatus(CollectStatus.YI_CAI_JI.getCode());
                tInCollectInvoice.setCollectStatusName(CollectStatus.YI_CAI_JI.getName());
                tInCollectInvoice.setInvoiceType(invoiceType);
                // 发票类型
                tInCollectInvoice.setInvoiceTypeName(DictUtils.getDictLabel("in_invoice_type", invoiceType));
                // 发票号码
                tInCollectInvoice.setInvoiceNo(inputComplianceValidateFullInvoiceInfo.getInvoiceNumber());
                // 发票代码
                tInCollectInvoice.setInvoiceCode(inputComplianceValidateFullInvoiceInfo.getInvoiceCode());
                // 开票日期：YYYY-MM-DD
                tInCollectInvoice.setInvoiceDate(inputComplianceValidateFullInvoiceInfo.getBillingDate());
                // 购方开户行账户
                tInCollectInvoice.setBuyerBank(inputComplianceValidateFullInvoiceInfo.getPurchaserBank());
                // 机器编号
                // tInCollectInvoice.setM(inputComplianceValidateFullInvoiceInfo.getMachineCode());
                // 收货人
                // tInCollectInvoice.setBuyerBank(inputComplianceValidateFullInvoiceInfo.getReceivingClerk());
                // 销方税号
                tInCollectInvoice.setSellerNumber(inputComplianceValidateFullInvoiceInfo.getSalesTaxNo());
                // 购方名称
                tInCollectInvoice.setBuyerName(inputComplianceValidateFullInvoiceInfo.getPurchaserName());
                // 购方名称
                tInCollectInvoice.setCheckCode(inputComplianceValidateFullInvoiceInfo.getCheckCode());
                // 合计税额[两位小数]
                tInCollectInvoice.setTax(inputComplianceValidateFullInvoiceInfo.getTotalTax());
                // 合计金额[两位小数]
                tInCollectInvoice.setFeeWithoutTax(BigDecimal.valueOf(inputComplianceValidateFullInvoiceInfo.getTotalAmount()));
                // 销方地址电话
                tInCollectInvoice.setSellerAddress(inputComplianceValidateFullInvoiceInfo.getSalesAddressPhone());
                // 销方名称
                tInCollectInvoice.setSellerName(inputComplianceValidateFullInvoiceInfo.getSalesName());
                // 购方税号
                tInCollectInvoice.setBuyerNumber(inputComplianceValidateFullInvoiceInfo.getPurchaserTaxNo());
                // 销方开户行账户
                tInCollectInvoice.setSellerAccount(inputComplianceValidateFullInvoiceInfo.getSalesBank());
                // 购方地址电话
                tInCollectInvoice.setBuyerAddress(inputComplianceValidateFullInvoiceInfo.getPurchaserAddressPhone());
                // 发票状态：0-正常，1-失控， 2-作废，3-红冲，4-异常，7-部分红冲，8-全额红冲
                tInCollectInvoice.setInvoiceStatus(Integer.parseInt(inputComplianceValidateFullInvoiceInfo.getState()));
                tInCollectInvoice.setInvoiceStatusName(DictUtils.getDictLabel("invoice_status", inputComplianceValidateFullInvoiceInfo.getState()));
                // 备注
                tInCollectInvoice.setRemark(inputComplianceValidateFullInvoiceInfo.getRemarks());
                // 价税合计
                tInCollectInvoice.setFee(new BigDecimal(inputComplianceValidateFullInvoiceInfo.getAmountTax()));
                // 买方电话
                tInCollectInvoice.setBuyerTel(inputComplianceValidateFullInvoiceInfo.getPurchaserPhone());
                // 车辆识别代号/车架号码
                tInCollectInvoice.setVoucherNumber(inputComplianceValidateFullInvoiceInfo.getVehicleNo());
                // 账号
                tInCollectInvoice.setSellerAccount(inputComplianceValidateFullInvoiceInfo.getSalesBankNo());
                // 销方地址电话
                tInCollectInvoice.setSellerTel(inputComplianceValidateFullInvoiceInfo.getSalesPhone());
                // 销方地址电话
                tInCollectInvoice.setSellerTel(inputComplianceValidateFullInvoiceInfo.getSalesPhone());

                // 查验状态
                tInCollectInvoice.setCheckStatus(CheckStatus.CHA_YAN_TONG_GUO.getCode());
                tInCollectInvoice.setCheckStatusName(CheckStatus.CHA_YAN_TONG_GUO.getName());
                //
                tInCollectInvoice.setIsRed(0);
                tInCollectInvoice.setIsRedName("非红票");
                // 发票地址
                tInCollectInvoice.setInvoiceUrl(inputComplianceValidateFullInvoiceInfo.getOfficialfileUrl());

                // 明细 t_in_collect_invoice_entry
                List<TInCollectInvoiceEntry> tInCollectInvoiceEntryList = new ArrayList<>();

                // t_in_invoice 对象保存
                TInInvoice tInInvoice = new TInInvoice();
                BeanUtils.copyProperties(tInCollectInvoice, tInInvoice);
                // FIXME 初始的报销状态？
                tInInvoice.setSubmitStatus(SubmitStatus.NOT_REIMBURSED.getCode());
                tInInvoice.setSubmitStatusName(SubmitStatus.NOT_REIMBURSED.getName());
                // 发票备注
                tInInvoice.setInvoiceRemark(inputComplianceValidateFullInvoiceInfo.getRemarks());
                // 票夹
                tInInvoice.setFolderId(tInCollect.getFolderId());
                // 是否蓝票
                tInInvoice.setIsRed(IsRed.BLUE.getCode());
                // 入账状态
                tInInvoice.setAccountStatus(AccountStatus.NOT_ACCOUNTED.getCode());
                tInInvoice.setAccountStatusName(AccountStatus.NOT_ACCOUNTED.getName());
                // 处理状态
                tInInvoice.setProcessStatus(ProcessStatus.INVOICED.getCode());
                tInInvoice.setProcessStatusName(ProcessStatus.INVOICED.getName());
                // 采集状态
                tInInvoice.setCollectStatus(CollectStatus.YI_CAI_JI.getCode());
                tInInvoice.setCollectStatusName(CollectStatus.YI_CAI_JI.getName());
                // 签收状态
                tInInvoice.setSignStatus(SignStatus.SIGNED.getCode());
                tInInvoice.setSignStatusName(SignStatus.SIGNED.getName());

                // 明细
                // 51:数电票（铁路电子客票）
                TInInvoice51 tInInvoice51 = new TInInvoice51();
                if(invoiceType.equals(InInvoiceType.DIGITAL_ELECTRIC_INVOICE_RAILWAY_E_TICKET.getCode())){
                    BeanUtils.copyProperties(tInInvoice, tInInvoice51);
                    // FIXME 字段对应需要重新检查，需要手动指定字段赋值
                    BeanUtils.copyProperties(inputComplianceValidateFullInvoiceInfo, tInInvoice51);
                    tInInvoice51.setFileAddress(inputComplianceValidateFullInvoiceInfo.getOfficialfileUrl());
                    tInInvoice51.setInvoiceType(InInvoiceType.DIGITAL_ELECTRIC_INVOICE_RAILWAY_E_TICKET.getCode());
                    tInInvoice51.setInvoiceTypeName(InInvoiceType.DIGITAL_ELECTRIC_INVOICE_RAILWAY_E_TICKET.getName());
                    tInInvoice51.setNoteType(NoteType.ZENGZHISHUI.getCode()+"");
                    tInInvoice51.setNoteName(NoteType.ZENGZHISHUI.getName());
                    tInInvoice51.setElectronicNo(inputComplianceValidateFullInvoiceInfo.getEInvoiceNumber());
                    tInInvoice51.setEticketNumber(inputComplianceValidateFullInvoiceInfo.getETicketNumber());
                    tInInvoice51.setInvoiceDate(inputComplianceValidateFullInvoiceInfo.getBillingDate());
                    tInInvoice51.setPurchaserName(inputComplianceValidateFullInvoiceInfo.getPurchaserName());
                    tInInvoice51.setPurchaserTaxNo(inputComplianceValidateFullInvoiceInfo.getPurchaserTaxNo());
                    tInInvoice51.setSaleName(inputComplianceValidateFullInvoiceInfo.getSalesName());
                    tInInvoice51.setSaleTaxNo(inputComplianceValidateFullInvoiceInfo.getSalesTaxNo());
                    tInInvoice51.setRemark(inputComplianceValidateFullInvoiceInfo.getRemarks());
                    tInInvoice51.setTotalAmount(new BigDecimal(inputComplianceValidateFullInvoiceInfo.getTotalAmount()));
                    tInInvoice51.setTotalTax(inputComplianceValidateFullInvoiceInfo.getTotalTax());
                    tInInvoice51.setAmountTax(new BigDecimal(inputComplianceValidateFullInvoiceInfo.getAmountTax()));
                    // FIXME 是否 DeductTax = EffectiveTax
                    tInInvoice51.setDeductTax(tInInvoice.getDeductTax());
                    // FIXME 是否 Drawer = Name
                    tInInvoice51.setDrawer(inputComplianceValidateFullInvoiceInfo.getName());
                    // FIXME 是否 LeaveCity = FromStation
                    tInInvoice51.setLeaveCity(inputComplianceValidateFullInvoiceInfo.getFromStation());
                    // FIXME 是否 ArriveCity = ToStation
                    tInInvoice51.setArriveCity(inputComplianceValidateFullInvoiceInfo.getToStation());
                    // 车次
                    tInInvoice51.setTrainNumber(inputComplianceValidateFullInvoiceInfo.getTrainNumber());
                    // 身份证号码/组织机构代码
                    tInInvoice51.setIdNum(inputComplianceValidateFullInvoiceInfo.getIdCardNo());
                    // 席别
                    tInInvoice51.setTrainSeat(inputComplianceValidateFullInvoiceInfo.getSeatLevel());
                    // 出发时间(铁路电子客票
                    tInInvoice51.setLeaveTime(inputComplianceValidateFullInvoiceInfo.getTravelDate());
                    // FIXME 到达时间？
                    tInInvoice51.setArriveTime(null);
                    // 影像
                    tInInvoice51.setHasPicture(0);
                    tInInvoice51.setHasPictureName("无");
                    // FIXME 查验状态
                    tInInvoice51.setInspectionTime(DateUtils.getNowDate());
                    tInInvoice51.setInspectionStatus(1);
                    tInInvoice51.setInspectionStatusName("查验通过");
                    tInInvoice51.setInspectionErrorDesc("");
                    // FIXME 合规
                    tInInvoice51.setIsComplianceCollect(IsComplianceCollect.HEGUI.getCode());
                    tInInvoice51.setIsComplianceCollectName(IsComplianceCollect.HEGUI.getName());
                    tInInvoice51.setComplianceCollectDesc("");
                    // FIXME 校验
                    tInInvoice51.setVerifyStatus(VerifyStatus.CHA_YAN_TONG_GUO.getCode());
                    tInInvoice51.setVerifyStatusName(VerifyStatus.CHA_YAN_TONG_GUO.getName());
                    // 发票状态：0-正常，1-失控， 2-作废，3-红冲，4-异常，7-部分红
                    //冲，8-全额红冲
                    tInInvoice51.setInvoiceState(Integer.parseInt(inputComplianceValidateFullInvoiceInfo.getState()));
                    tInInvoice51.setInvoiceStateName(DictUtils.getDictLabel("invoice_status", inputComplianceValidateFullInvoiceInfo.getState()));
                    // FIXME 签收
                    tInInvoice51.setSignStatus(SignStatus.SIGNED.getCode());
                    tInInvoice51.setSignStatusName(SignStatus.SIGNED.getName());
                    // FIXME 推送时间
                    tInInvoice51.setPushTime(null);
                    //
                    tInInvoice51.setCollectinvUseType(null);
                    tInInvoice51.setId(null);
                    tInInvoice51.setInvoiceId(tInInvoice.getInvoiceId());
                }

                // 61:数电票（航空运输电子客票行程单）
                TInInvoice61 tInInvoice61 = new TInInvoice61();
                if(invoiceType.equals(InInvoiceType.DIGITAL_ELECTRIC_INVOICE_RAILWAY_E_TICKET.getCode())){
                    BeanUtils.copyProperties(tInInvoice, tInInvoice61);
                    // FIXME 字段对应需要重新检查，需要手动指定字段赋值
                    BeanUtils.copyProperties(inputComplianceValidateFullInvoiceInfo, tInInvoice61);
                    tInInvoice61.setInvoiceType(InInvoiceType.DIGITAL_ELECTRIC_INVOICE_RAILWAY_E_TICKET.getCode());
                    tInInvoice61.setInvoiceTypeName(InInvoiceType.DIGITAL_ELECTRIC_INVOICE_RAILWAY_E_TICKET.getName());
                    tInInvoice61.setNoteType(NoteType.ZENGZHISHUI.getCode()+"");
                    tInInvoice61.setNoteName(NoteType.ZENGZHISHUI.getName());
                    tInInvoice61.setElectronicNo(inputComplianceValidateFullInvoiceInfo.getEInvoiceNumber());
                    tInInvoice61.setEticketNumber(inputComplianceValidateFullInvoiceInfo.getETicketNumber());
                    tInInvoice61.setInvoiceDate(inputComplianceValidateFullInvoiceInfo.getBillingDate());
                    tInInvoice61.setUseRemark(inputComplianceValidateFullInvoiceInfo.getRemarks());
                    tInInvoice61.setTotalAmount(new BigDecimal(inputComplianceValidateFullInvoiceInfo.getTotalAmount()));
                    tInInvoice61.setTotalTax(inputComplianceValidateFullInvoiceInfo.getTotalTax());
                    // FIXME 其他税费
                    // tInInvoice61.setOtherTax(?);
                    tInInvoice61.setAmountTax(new BigDecimal(inputComplianceValidateFullInvoiceInfo.getAmountTax()));
                    // FIXME 是否 DeductTax = EffectiveTax
                    tInInvoice61.setDeductTax(tInInvoice.getDeductTax());
                    // FIXME 是否 Drawer = Name
                    tInInvoice61.setDrawer(inputComplianceValidateFullInvoiceInfo.getName());
                    // FIXME 民航发展基金
                    // tInInvoice61.setCivilAviationFund(?);
                    // FIXME 民航发展基金
                    // tInInvoice61.setCivilAviationFund(?);
                    // FIXME 是否 LeaveCity = FromStation
                    tInInvoice61.setLeaveCity(inputComplianceValidateFullInvoiceInfo.getFromStation());
                    // FIXME 是否 ArriveCity = ToStation
                    tInInvoice61.setArriveCity(inputComplianceValidateFullInvoiceInfo.getToStation());
                    // 航班
                    tInInvoice61.setTrainNumber(inputComplianceValidateFullInvoiceInfo.getTrainNumber());
                    // FIXME 车牌号
                    // tInInvoice61.setCarNo(?);
                    // 身份证号码/组织机构代码
                    tInInvoice61.setIdNum(inputComplianceValidateFullInvoiceInfo.getIdCardNo());
                    // 席别
                    tInInvoice61.setTrainSeat(inputComplianceValidateFullInvoiceInfo.getSeatLevel());
                    // 出发时间(铁路电子客票
                    tInInvoice61.setLeaveTime(inputComplianceValidateFullInvoiceInfo.getTravelDate());
                    // FIXME 到达时间？
                    tInInvoice61.setArriveTime(null);
                    // FIXME 保险费
                    // tInInvoice61.setPremium(?);
                    // 影像
                    tInInvoice61.setHasPicture(0);
                    tInInvoice61.setHasPictureName("无");
                    // FIXME 查验状态
                    tInInvoice61.setInspectionTime(DateUtils.getNowDate());
                    tInInvoice61.setInspectionStatus(1);
                    tInInvoice61.setInspectionStatusName("查验通过");
                    tInInvoice61.setInspectionErrorDesc("");
                    // FIXME 合规
                    tInInvoice61.setIsComplianceCollect(IsComplianceCollect.HEGUI.getCode());
                    tInInvoice61.setIsComplianceCollectName(IsComplianceCollect.HEGUI.getName());
                    tInInvoice61.setComplianceCollectDesc("");
                    // FIXME 校验
                    tInInvoice61.setVerifyStatus(VerifyStatus.CHA_YAN_TONG_GUO.getCode());
                    tInInvoice61.setVerifyStatusName(VerifyStatus.CHA_YAN_TONG_GUO.getName());
                    // 发票状态：0-正常，1-失控， 2-作废，3-红冲，4-异常，7-部分红
                    //冲，8-全额红冲
                    tInInvoice61.setInvoiceState(Integer.parseInt(inputComplianceValidateFullInvoiceInfo.getState()));
                    tInInvoice61.setInvoiceStateName(DictUtils.getDictLabel("invoice_status", inputComplianceValidateFullInvoiceInfo.getState()));

                    tInInvoice61.setId(null);
                    tInInvoice61.setInvoiceId(tInInvoice.getInvoiceId());
                }

                // 11:增值税普通发票(卷式)
                TInInvoice11 tInInvoice11 = new TInInvoice11();
                if(invoiceType.equals(InInvoiceType.VALUE_ADDED_TAX_GENERAL_INVOICE_ROLL_TYPE.getCode())){
                    BeanUtils.copyProperties(tInInvoice, tInInvoice11);
                    // FIXME 字段对应需要重新检查，需要手动指定字段赋值
                    BeanUtils.copyProperties(inputComplianceValidateFullInvoiceInfo, tInInvoice11);
                    tInInvoice11.setFileAddress(inputComplianceValidateFullInvoiceInfo.getOfficialfileUrl());
                    tInInvoice11.setInvoiceType(InInvoiceType.VALUE_ADDED_TAX_GENERAL_INVOICE_ROLL_TYPE.getCode());
                    tInInvoice11.setInvoiceTypeName(InInvoiceType.VALUE_ADDED_TAX_GENERAL_INVOICE_ROLL_TYPE.getName());
                    tInInvoice11.setNoteType(NoteType.ZENGZHISHUI.getCode()+"");
                    tInInvoice11.setNoteName(NoteType.ZENGZHISHUI.getName());
                    tInInvoice11.setInvoiceDate(inputComplianceValidateFullInvoiceInfo.getBillingDate());
                    tInInvoice11.setPurchaserName(inputComplianceValidateFullInvoiceInfo.getPurchaserName());
                    tInInvoice11.setPurchaserTaxNo(inputComplianceValidateFullInvoiceInfo.getPurchaserTaxNo());
                    tInInvoice11.setSaleName(inputComplianceValidateFullInvoiceInfo.getSalesName());
                    tInInvoice11.setSaleTaxNo(inputComplianceValidateFullInvoiceInfo.getSalesTaxNo());
                    tInInvoice11.setRemark(inputComplianceValidateFullInvoiceInfo.getRemarks());
                    tInInvoice11.setTotalAmount(new BigDecimal(inputComplianceValidateFullInvoiceInfo.getTotalAmount()));
                    tInInvoice11.setTotalTax(inputComplianceValidateFullInvoiceInfo.getTotalTax());
                    tInInvoice11.setAmountTax(new BigDecimal(inputComplianceValidateFullInvoiceInfo.getAmountTax()));

                    // FIXME 是否 DeductTax = EffectiveTax
                    tInInvoice11.setDeductTax(tInInvoice.getDeductTax());

                    // 影像
                    tInInvoice11.setHasPicture(0);
                    tInInvoice11.setHasPictureName("无");
                    // FIXME 查验状态
                    tInInvoice11.setInspectionTime(DateUtils.getNowDate());
                    tInInvoice11.setInspectionStatus(1);
                    tInInvoice11.setInspectionStatusName("查验通过");
                    tInInvoice11.setInspectionErrorDesc("");
                    // FIXME 合规
                    tInInvoice11.setIsComplianceCollect(IsComplianceCollect.HEGUI.getCode());
                    tInInvoice11.setIsComplianceCollectName(IsComplianceCollect.HEGUI.getName());
                    tInInvoice11.setComplianceCollectDesc("");
                    // FIXME 校验
                    tInInvoice11.setVerifyStatus(VerifyStatus.CHA_YAN_TONG_GUO.getCode());
                    tInInvoice11.setVerifyStatusName(VerifyStatus.CHA_YAN_TONG_GUO.getName());
                    // 发票状态：0-正常，1-失控， 2-作废，3-红冲，4-异常，7-部分红
                    //冲，8-全额红冲
                    tInInvoice11.setInvoiceState(Integer.parseInt(inputComplianceValidateFullInvoiceInfo.getState()));
                    tInInvoice11.setInvoiceStateName(DictUtils.getDictLabel("invoice_status", inputComplianceValidateFullInvoiceInfo.getState()));
                    // FIXME 签收
                    tInInvoice11.setSignStatus(SignStatus.SIGNED.getCode());
                    tInInvoice11.setSignStatusName(SignStatus.SIGNED.getName());
                    // FIXME 推送时间
                    tInInvoice11.setPushTime(null);
                    //
                    tInInvoice11.setCollectinvUseType(null);
                    tInInvoice11.setId(null);
                    tInInvoice11.setInvoiceId(tInInvoice.getInvoiceId());
                }

                // 14: 道路通行费电子普通发票
                TInInvoice14 tInInvoice14 = new TInInvoice14();
                if(invoiceType.equals(InInvoiceType.VALUE_ADDED_TAX_ELECTRONIC_GENERAL_INVOICE_FOR_TOLL.getCode())){
                    BeanUtils.copyProperties(tInInvoice, tInInvoice14);
                    // FIXME 字段对应需要重新检查，需要手动指定字段赋值
                    BeanUtils.copyProperties(inputComplianceValidateFullInvoiceInfo, tInInvoice14);
                    tInInvoice14.setFileAddress(inputComplianceValidateFullInvoiceInfo.getOfficialfileUrl());
                    tInInvoice14.setInvoiceType(InInvoiceType.VALUE_ADDED_TAX_ELECTRONIC_GENERAL_INVOICE_FOR_TOLL.getCode());
                    tInInvoice14.setInvoiceTypeName(InInvoiceType.VALUE_ADDED_TAX_ELECTRONIC_GENERAL_INVOICE_FOR_TOLL.getName());
                    tInInvoice14.setNoteType(NoteType.ZENGZHISHUI.getCode()+"");
                    tInInvoice14.setNoteName(NoteType.ZENGZHISHUI.getName());
                    tInInvoice14.setInvoiceDate(inputComplianceValidateFullInvoiceInfo.getBillingDate());
                    tInInvoice14.setPurchaserName(inputComplianceValidateFullInvoiceInfo.getPurchaserName());
                    tInInvoice14.setPurchaserTaxNo(inputComplianceValidateFullInvoiceInfo.getPurchaserTaxNo());
                    tInInvoice14.setSaleName(inputComplianceValidateFullInvoiceInfo.getSalesName());
                    tInInvoice14.setSaleTaxNo(inputComplianceValidateFullInvoiceInfo.getSalesTaxNo());
                    tInInvoice14.setRemark(inputComplianceValidateFullInvoiceInfo.getRemarks());
                    tInInvoice14.setTotalAmount(new BigDecimal(inputComplianceValidateFullInvoiceInfo.getTotalAmount()));
                    tInInvoice14.setTotalTax(inputComplianceValidateFullInvoiceInfo.getTotalTax());
                    tInInvoice14.setAmountTax(new BigDecimal(inputComplianceValidateFullInvoiceInfo.getAmountTax()));

                    // FIXME 是否 DeductTax = EffectiveTax
                    tInInvoice14.setDeductTax(tInInvoice.getDeductTax());

                    // 影像
                    tInInvoice14.setHasPicture(0);
                    tInInvoice14.setHasPictureName("无");
                    // FIXME 查验状态
                    tInInvoice14.setInspectionTime(DateUtils.getNowDate());
                    tInInvoice14.setInspectionStatus(1);
                    tInInvoice14.setInspectionStatusName("查验通过");
                    tInInvoice14.setInspectionErrorDesc("");
                    // FIXME 合规
                    tInInvoice14.setIsComplianceCollect(IsComplianceCollect.HEGUI.getCode());
                    tInInvoice14.setIsComplianceCollectName(IsComplianceCollect.HEGUI.getName());
                    tInInvoice14.setComplianceCollectDesc("");
                    // FIXME 校验
                    tInInvoice14.setVerifyStatus(VerifyStatus.CHA_YAN_TONG_GUO.getCode());
                    tInInvoice14.setVerifyStatusName(VerifyStatus.CHA_YAN_TONG_GUO.getName());
                    // 发票状态：0-正常，1-失控， 2-作废，3-红冲，4-异常，7-部分红
                    //冲，8-全额红冲
                    tInInvoice14.setInvoiceState(Integer.parseInt(inputComplianceValidateFullInvoiceInfo.getState()));
                    tInInvoice14.setInvoiceStateName(DictUtils.getDictLabel("invoice_status", inputComplianceValidateFullInvoiceInfo.getState()));
                    // FIXME 签收
                    tInInvoice14.setSignStatus(SignStatus.SIGNED.getCode());
                    tInInvoice14.setSignStatusName(SignStatus.SIGNED.getName());
                    // FIXME 推送时间
                    tInInvoice14.setPushTime(null);
                    //
                    tInInvoice14.setCollectinvUseType(null);
                    tInInvoice14.setId(null);
                    tInInvoice14.setInvoiceId(tInInvoice.getInvoiceId());
                }

                // 15:二手车销售统一发票
                TInInvoice15 tInInvoice15 = new TInInvoice15();
                if(invoiceType.equals(InInvoiceType.USED_CAR_SALES_UNIFIED_INVOICE.getCode())){
                    BeanUtils.copyProperties(tInInvoice, tInInvoice15);
                    // FIXME 字段对应需要重新检查，需要手动指定字段赋值
                    BeanUtils.copyProperties(inputComplianceValidateFullInvoiceInfo, tInInvoice15);
                    tInInvoice15.setFileAddress(inputComplianceValidateFullInvoiceInfo.getOfficialfileUrl());
                    tInInvoice15.setInvoiceType(InInvoiceType.USED_CAR_SALES_UNIFIED_INVOICE.getCode());
                    tInInvoice15.setInvoiceTypeName(InInvoiceType.USED_CAR_SALES_UNIFIED_INVOICE.getName());
                    tInInvoice15.setNoteType(NoteType.ZENGZHISHUI.getCode()+"");
                    tInInvoice15.setNoteName(NoteType.ZENGZHISHUI.getName());
                    tInInvoice15.setInvoiceDate(inputComplianceValidateFullInvoiceInfo.getBillingDate());
                    tInInvoice15.setPurchaserName(inputComplianceValidateFullInvoiceInfo.getPurchaserName());
                    tInInvoice15.setPurchaserTaxNo(inputComplianceValidateFullInvoiceInfo.getPurchaserTaxNo());
                    tInInvoice15.setSaleName(inputComplianceValidateFullInvoiceInfo.getSalesName());
                    tInInvoice15.setSaleTaxNo(inputComplianceValidateFullInvoiceInfo.getSalesTaxNo());
                    tInInvoice15.setRemark(inputComplianceValidateFullInvoiceInfo.getRemarks());
                    tInInvoice15.setTotalAmount(new BigDecimal(inputComplianceValidateFullInvoiceInfo.getTotalAmount()));
                    tInInvoice15.setTotalTax(inputComplianceValidateFullInvoiceInfo.getTotalTax());
                    tInInvoice15.setAmountTax(new BigDecimal(inputComplianceValidateFullInvoiceInfo.getAmountTax()));

                    // FIXME 是否 DeductTax = EffectiveTax
                    tInInvoice15.setDeductTax(tInInvoice.getDeductTax());

                    // 影像
                    tInInvoice15.setHasPicture(0);
                    tInInvoice15.setHasPictureName("无");
                    // FIXME 查验状态
                    tInInvoice15.setInspectionTime(DateUtils.getNowDate());
                    tInInvoice15.setInspectionStatus(1);
                    tInInvoice15.setInspectionStatusName("查验通过");
                    tInInvoice15.setInspectionErrorDesc("");
                    // FIXME 合规
                    tInInvoice15.setIsComplianceCollect(IsComplianceCollect.HEGUI.getCode());
                    tInInvoice15.setIsComplianceCollectName(IsComplianceCollect.HEGUI.getName());
                    tInInvoice15.setComplianceCollectDesc("");
                    // FIXME 校验
                    tInInvoice15.setVerifyStatus(VerifyStatus.CHA_YAN_TONG_GUO.getCode());
                    tInInvoice15.setVerifyStatusName(VerifyStatus.CHA_YAN_TONG_GUO.getName());
                    // 发票状态：0-正常，1-失控， 2-作废，3-红冲，4-异常，7-部分红
                    //冲，8-全额红冲
                    tInInvoice15.setInvoiceState(Integer.parseInt(inputComplianceValidateFullInvoiceInfo.getState()));
                    tInInvoice15.setInvoiceStateName(DictUtils.getDictLabel("invoice_status", inputComplianceValidateFullInvoiceInfo.getState()));
                    // FIXME 签收
                    tInInvoice15.setSignStatus(SignStatus.SIGNED.getCode());
                    tInInvoice15.setSignStatusName(SignStatus.SIGNED.getName());
                    // FIXME 推送时间
                    tInInvoice11.setPushTime(null);
                    //
                    tInInvoice15.setCollectinvUseType(null);
                    tInInvoice15.setId(null);
                    tInInvoice15.setInvoiceId(tInInvoice.getInvoiceId());
                }

                // 查验接口不返回 83，84

                List<TInInvoiceEntry> tInInvoiceEntryList = new ArrayList<>();

                List<InputComplianceValidateInvoice> invoiceList = inputComplianceValidateFullInvoiceInfo.getInvoiceList();
                for(InputComplianceValidateInvoice inputComplianceValidateInvoice : invoiceList){
                    TInCollectInvoiceEntry tInCollectInvoiceEntry = new TInCollectInvoiceEntry();
                    BeanUtils.copyProperties(tInCollectInvoice, tInCollectInvoiceEntry);
                    // 单价
                    tInCollectInvoiceEntry.setPrice(new BigDecimal(inputComplianceValidateInvoice.getUnitPrice()));
                    // 行号
                    tInCollectInvoiceEntry.setLineNo(Integer.parseInt(inputComplianceValidateInvoice.getRowNo()));
                    // 税率
                    tInCollectInvoiceEntry.setTaxRate(new BigDecimal(inputComplianceValidateInvoice.getTaxRate()));
                    // 金额
                    tInCollectInvoiceEntry.setWithoutAmount(new BigDecimal(inputComplianceValidateInvoice.getAmount()));
                    // 单位
                    tInCollectInvoiceEntry.setUnit(inputComplianceValidateInvoice.getUnit());
                    // 数量
                    tInCollectInvoiceEntry.setQty(new BigDecimal(inputComplianceValidateInvoice.getQuantity()));
                    // 规格型号
                    tInCollectInvoiceEntry.setSpecificatCode(inputComplianceValidateInvoice.getSpecificationModel());
                    // 税额
                    tInCollectInvoiceEntry.setTax(new BigDecimal(inputComplianceValidateInvoice.getTax()));
                    // 货物或应税劳务名称
                    tInCollectInvoiceEntry.setProductName(inputComplianceValidateInvoice.getCommodityName());
                    // 货物或应税劳务编码
                    tInCollectInvoiceEntry.setProductCode(inputComplianceValidateInvoice.getCommodityCode());
                    tInCollectInvoiceEntryList.add(tInCollectInvoiceEntry);

                    TInInvoiceEntry tInInvoiceEntry = new TInInvoiceEntry();
                    BeanUtils.copyProperties(tInCollectInvoiceEntry, tInInvoiceEntry);
                    tInInvoiceEntryList.add(tInInvoiceEntry);


                    List<TInInvoice61Entry> tInInvoice61EntryList = new ArrayList<>();
                    if(invoiceType.equals(InInvoiceType.DIGITAL_ELECTRIC_INVOICE_AIR_TRANSPORT_E_TICKET.getCode())){
                        TInInvoice61Entry tInInvoice61Entry = new TInInvoice61Entry();
                        BeanUtils.copyProperties(tInInvoice61, tInInvoice61Entry);
                        // FIXME 字段对应需要重新检查，需要手动指定字段赋值
                        BeanUtils.copyProperties(inputComplianceValidateInvoice, tInInvoice61Entry);
                        tInInvoice61Entry.setFromStation(inputComplianceValidateInvoice.getFromCity());
                        tInInvoice61Entry.setToStation(inputComplianceValidateInvoice.getToCity());
                        // 航班号
                        tInInvoice61Entry.setFlightNo(inputComplianceValidateInvoice.getFlightNumber());
                        tInInvoice61Entry.setTravelDate(inputComplianceValidateInvoice.getCarriageDate());
                        tInInvoice61Entry.setTravelTime(inputComplianceValidateInvoice.getFlightDate());
                        tInInvoice61Entry.setSeatLevel(inputComplianceValidateInvoice.getSeatLevel());
                        tInInvoice61.setId(null);
                        tInInvoice61.setInvoiceId(tInInvoice.getInvoiceId());
                        tInInvoice61EntryList.add(tInInvoice61Entry);
                    }
                    tInInvoice61.setTInInvoice61EntryList(tInInvoice61EntryList);
                }
                tInCollectInvoice.setTInCollectInvoiceEntryList(tInCollectInvoiceEntryList);
                tInCollectInvoiceService.insertTInCollectInvoice(tInCollectInvoice);

                tInInvoice.setTInInvoiceEntryList(tInInvoiceEntryList);
                tInInvoiceService.insertTInInvoice(tInInvoice);
                // 进项增值税副表
                // 51:数电票（铁路电子客票） -增
                // 61:数电票（航空运输电子客票行程单） -增
                // 11:增值税普通发票(卷式) -增
                // 保存副表
                if(invoiceType.equals(InInvoiceType.DIGITAL_ELECTRIC_INVOICE_RAILWAY_E_TICKET.getCode())){
                    tInInvoice51.setInvoiceId(tInInvoice.getInvoiceId());
                    tInInvoice51Service.insertTInInvoice51(tInInvoice51);
                }
                if(invoiceType.equals(InInvoiceType.DIGITAL_ELECTRIC_INVOICE_RAILWAY_E_TICKET.getCode())){
                    tInInvoice61.setInvoiceId(tInInvoice.getInvoiceId());
                    tInInvoice61Service.insertTInInvoice61(tInInvoice61);
                }
                if(invoiceType.equals(InInvoiceType.VALUE_ADDED_TAX_GENERAL_INVOICE_ROLL_TYPE.getCode())){
                    tInInvoice11.setInvoiceId(tInInvoice.getInvoiceId());
                    tInInvoice11Service.insertTInInvoice11(tInInvoice11);
                }
                //
                if(inCollectEntry != null){
                    inCollectEntry.setCheckStatusName(CheckStatus.CHA_YAN_TONG_GUO.getName());
                    inCollectEntry.setEnterStatus(EnterStatus.RU_CHI_CHENG_GONG.getCode());
                    inCollectEntry.setEnterStatusName(EnterStatus.RU_CHI_CHENG_GONG.getName());
                    inCollectEntry.setCollectTime(DateUtils.getNowDate());
                    inCollectEntry.setUpdateTime(DateUtils.getNowDate());
                }
                tInCollectMapper.updateTInCollectEntry(inCollectEntry);
                collectSuccessQty ++;
                checkSuccessQty ++;
            }
        }
        // 更新各数量字段
        tInCollect.setCollectFail(collectFailQty);
        tInCollect.setCollectRepeat(collectRepeatQty);
        tInCollect.setCollectSuccess(collectSuccessQty);
        tInCollect.setCollectException(collectExceptionQty);
        tInCollect.setCollectSuccess(checkSuccessQty);
        tInCollect.setCheckFail(checkFailQty);
        tInCollect.setCollectStatus(CollectStatus.YI_WAN_CHENG.getCode());
        tInCollect.setCollectStatusName(CollectStatus.YI_WAN_CHENG.getName());
        tInCollectMapper.updateTInCollect(tInCollect);
    }

    /**
        根据识别接口返回数据入池(增值税)
     */
    private int checkInInvoicePool(ImageInvoicesRecogcollectMediaInvoice imageInvoicesRecogcollectMediaInvoice, TInCollectInvoice tInCollectInvoice){
        // 增值税发票入池
        if (imageInvoicesRecogcollectMediaInvoice.getNoteType().equals(1L)) {
            String invoiceType = imageInvoicesRecogcollectMediaInvoice.getInvoiceType();
            // 进项增值税发票对象
            TInInvoice inInvoice = new TInInvoice();
            BeanUtils.copyProperties(tInCollectInvoice, inInvoice);
            inInvoice.setId(null);
            // 入账状态
            inInvoice.setAccountStatus(AccountStatus.NOT_ACCOUNTED.getCode());
            inInvoice.setAccountStatusName(AccountStatus.NOT_ACCOUNTED.getName());
            // 处理状态
            inInvoice.setProcessStatus(ProcessStatus.INVOICED.getCode());
            inInvoice.setProcessStatusName(ProcessStatus.INVOICED.getName());
            // 报销状态
            inInvoice.setSubmitStatus(SubmitStatus.NOT_REIMBURSED.getCode());
            inInvoice.setSubmitStatusName(SubmitStatus.NOT_REIMBURSED.getName());
            // 根据isDeduct 是否抵扣，0：否 ，1：是 转为抵扣认证状态
            if(imageInvoicesRecogcollectMediaInvoice.getIsDeduct().equals("0")){
                inInvoice.setDeductible(Deductible.WEI_REN_ZHENG.getCode());
                inInvoice.setDeductibleName(Deductible.WEI_REN_ZHENG.getName());
            } else {
                inInvoice.setDeductible(Deductible.REN_ZHENG_TONG_GUO.getCode());
                inInvoice.setDeductibleName(Deductible.REN_ZHENG_TONG_GUO.getName());
            }
            // 抵扣日期
            inInvoice.setDeductibleDate(imageInvoicesRecogcollectMediaInvoice.getInvDeduDate());
            //

            // 明细
            List<TInInvoiceEntry> tInInvoiceEntryList = new ArrayList<>();
            for(TInCollectInvoiceEntry collectInvoiceEntry : tInCollectInvoice.getTInCollectInvoiceEntryList()){
                TInInvoiceEntry invoiceEntry = new TInInvoiceEntry();
                BeanUtils.copyProperties(collectInvoiceEntry, invoiceEntry);
                invoiceEntry.setId(null);
                tInInvoiceEntryList.add(invoiceEntry);
            }
            inInvoice.setTInInvoiceEntryList(tInInvoiceEntryList);
            // 如果存在副表 则也需要保存  51，61，83，84，11，14，15
            if(tInInvoiceService.insertTInInvoice(inInvoice) == 1){
                if(invoiceType.equals(InInvoiceType.DIGITAL_ELECTRIC_INVOICE_RAILWAY_E_TICKET.getCode())
                || invoiceType.equals(InInvoiceType.DIGITAL_ELECTRIC_INVOICE_AIR_TRANSPORT_E_TICKET.getCode())
                || invoiceType.equals(InInvoiceType.DIGITAL_ELECTRIC_MOTOR_VEHICLE_SALES_UNIFIED_INVOICE.getCode())
                || invoiceType.equals(InInvoiceType.DIGITAL_ELECTRIC_USED_CAR_SALES_UNIFIED_INVOICE.getCode())
                || invoiceType.equals(InInvoiceType.VALUE_ADDED_TAX_GENERAL_INVOICE_ROLL_TYPE.getCode())
                || invoiceType.equals(InInvoiceType.VALUE_ADDED_TAX_ELECTRONIC_GENERAL_INVOICE_FOR_TOLL.getCode())
                || invoiceType.equals(InInvoiceType.USED_CAR_SALES_UNIFIED_INVOICE.getCode())
                ){
                    switch (invoiceType) {
                        // 51: 数电票（铁路电子客票）
                        case "51":
                            TInInvoice51 tInInvoice51 = new TInInvoice51();
                            BeanUtils.copyProperties(inInvoice, tInInvoice51);
                            BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInInvoice51);
                            tInInvoice51.setId(null);
                            tInInvoice51.setInvoiceId(inInvoice.getInvoiceId());
                            return tInInvoice51Service.insertTInInvoice51(tInInvoice51);
                        // 61:数电票（航空运输电子客票行程单）
                        case "61":
                            TInInvoice61 tInInvoice61 = new TInInvoice61();
                            BeanUtils.copyProperties(inInvoice, tInInvoice61);
                            BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInInvoice61);
                            tInInvoice61.setId(null);
                            tInInvoice61.setInvoiceId(inInvoice.getInvoiceId());
                            // 明细
                            List<TInInvoice61Entry> tInInvoice61EntryList = new ArrayList<>();
                            for(ImageInvoicesRecogcollectBizInvoiceTravel invoiceTrave : imageInvoicesRecogcollectMediaInvoice.getInvoiceTravelList()){
                                TInInvoice61Entry tInInvoice61Entry = new TInInvoice61Entry();
                                BeanUtils.copyProperties(invoiceTrave, tInInvoice61Entry);
                                tInInvoice61Entry.setId(null);
                                tInInvoice61EntryList.add(tInInvoice61Entry);
                            }
                            tInInvoice61.setTInInvoice61EntryList(tInInvoice61EntryList);
                            return tInInvoice61Service.insertTInInvoice61(tInInvoice61);
                        // 83 电子发票（机动车销售统一发票）
                        case "83":
                            TInInvoice83 tInInvoice83 = new TInInvoice83();
                            BeanUtils.copyProperties(inInvoice, tInInvoice83);
                            BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInInvoice83);
                            tInInvoice83.setId(null);
                            tInInvoice83.setInvoiceId(inInvoice.getInvoiceId());
                            return tInInvoice83Service.insertTInInvoice83(tInInvoice83);
                        // 84 电子发票（二手车销售统一发票）
                        case "84":
                            TInInvoice84 tInInvoice84 = new TInInvoice84();
                            BeanUtils.copyProperties(inInvoice, tInInvoice84);
                            BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInInvoice84);
                            tInInvoice84.setId(null);
                            tInInvoice84.setInvoiceId(inInvoice.getInvoiceId());
                            return tInInvoice84Service.insertTInInvoice84(tInInvoice84);
                        // 11:增值税普通发票(卷式)
                        case "11":
                            TInInvoice11 tInInvoice11 = new TInInvoice11();
                            BeanUtils.copyProperties(inInvoice, tInInvoice11);
                            BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInInvoice11);
                            tInInvoice11.setId(null);
                            tInInvoice11.setInvoiceId(inInvoice.getInvoiceId());
                            return tInInvoice11Service.insertTInInvoice11(tInInvoice11);
                        // 14: 道路通行费电子普通发票
                        case "14":
                            TInInvoice14 tInInvoice14 = new TInInvoice14();
                            BeanUtils.copyProperties(inInvoice, tInInvoice14);
                            BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInInvoice14);
                            tInInvoice14.setId(null);
                            tInInvoice14.setInvoiceId(inInvoice.getInvoiceId());
                            return tInInvoice14Service.insertTInInvoice14(tInInvoice14);
                        // 15:二手车销售统一发票
                        case "15":
                            TInInvoice15 tInInvoice15 = new TInInvoice15();
                            BeanUtils.copyProperties(inInvoice, tInInvoice15);
                            BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInInvoice15);
                            tInInvoice15.setId(null);
                            tInInvoice15.setInvoiceId(inInvoice.getInvoiceId());
                            return tInInvoice15Service.insertTInInvoice15(tInInvoice15);

                        default:
                            return 0;
                    }
                }
            }
        }
        return 0;
    }

    /**
     * 根据识别接口返回数据入池(非增值税)
    */
    private int checkInNonInvoicePool(ImageInvoicesRecogcollectMediaInvoice imageInvoicesRecogcollectMediaInvoice, TInCollectNonInvoice tInCollectNonInvoice){
        // 非增值税发票入池
        if (imageInvoicesRecogcollectMediaInvoice.getNoteType().equals(2L)) {
            // 非增值税主表 t_in_non_invoice
            TInNonInvoice tInNonInvoice = new TInNonInvoice();
            BeanUtils.copyProperties(tInCollectNonInvoice, tInNonInvoice);
            // 报销状态
            tInNonInvoice.setSubmitStatus(SubmitStatus.NOT_REIMBURSED.getCode());
            tInNonInvoice.setSubmitStatusName(SubmitStatus.NOT_REIMBURSED.getName());
            // 根据isDeduct 是否抵扣，0：否 ，1：是 转为抵扣认证状态
            if(imageInvoicesRecogcollectMediaInvoice.getIsDeduct().equals("0")){
                tInNonInvoice.setDeductible(Deductible.WEI_REN_ZHENG.getCode());
                tInNonInvoice.setDeductibleName(Deductible.WEI_REN_ZHENG.getName());
            } else {
                tInNonInvoice.setDeductible(Deductible.REN_ZHENG_TONG_GUO.getCode());
                tInNonInvoice.setDeductibleName(Deductible.REN_ZHENG_TONG_GUO.getName());
            }
            // 抵扣日期
            tInNonInvoice.setDeductibleDate(imageInvoicesRecogcollectMediaInvoice.getInvDeduDate());
            //
            tInNonInvoice.setId(null);
            if (tInNonInvoiceService.insertTInNonInvoice(tInNonInvoice) == 1){
                String invoiceType = imageInvoicesRecogcollectMediaInvoice.getInvoiceType();
                switch (invoiceType)
                {
                    // 火车票
                    case "1002":
                        TInNon1002 tInNon1002 = new TInNon1002();
                        BeanUtils.copyProperties(tInCollectNonInvoice, tInNon1002);
                        BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInNon1002);
                        tInNon1002.setId(null);
                        tInNon1002.setInvoiceId(tInNonInvoice.getInvoiceId());
                        return tInNonInvoiceService.insertTInNonInvoiceX(tInNon1002);
                    // 航空电子客票行程单
                    case "1003":
                        TInNon1003 tInNon1003 = new TInNon1003();
                        BeanUtils.copyProperties(tInCollectNonInvoice, tInNon1003);
                        BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInNon1003);
                        // 明细
                        List<TInNon1003Entry> tInNon1003EntryList = new ArrayList<>();
                        ImageInvoicesRecogcollectInvoiceAttached imageInvoicesRecogcollectInvoiceAttached = imageInvoicesRecogcollectMediaInvoice.getInvoiceAttached();
                        TInNon1003Entry tInNon1003Entry = new TInNon1003Entry();
                        BeanUtils.copyProperties(tInCollectNonInvoice, tInNon1003Entry);
                        BeanUtils.copyProperties(imageInvoicesRecogcollectInvoiceAttached, tInNon1003Entry);
                        tInNon1003Entry.setId(null);
                        tInNon1003EntryList.add(tInNon1003Entry);
                        tInNon1003.setId(null);
                        tInNon1003.setInvoiceId(tInNonInvoice.getInvoiceId());
                        return tInNonInvoiceService.insertTInNonInvoiceX(tInNon1003);
                    // 出租车发票
                    case "1004":
                        TInNon1004 tInNon1004 = new TInNon1004();
                        BeanUtils.copyProperties(tInCollectNonInvoice, tInNon1004);
                        BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInNon1004);
                        tInNon1004.setId(null);
                        tInNon1004.setInvoiceId(tInNonInvoice.getInvoiceId());
                        return tInNonInvoiceService.insertTInNonInvoiceX(tInNon1004);
                    // 通用定额发票
                    case "1005":
                        TInNon1005 tInNon1005 = new TInNon1005();
                        BeanUtils.copyProperties(tInCollectNonInvoice, tInNon1005);
                        BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInNon1005);
                        tInNon1005.setId(null);
                        tInNon1005.setInvoiceId(tInNonInvoice.getInvoiceId());
                        return tInNonInvoiceService.insertTInNonInvoiceX(tInNon1005);
                    // "公路水路客运发票"
                    case "1006":
                        TInNon1006 tInNon1006 = new TInNon1006();
                        BeanUtils.copyProperties(tInCollectNonInvoice, tInNon1006);
                        BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInNon1006);
                        tInNon1006.setId(null);
                        tInNon1006.setInvoiceId(tInNonInvoice.getInvoiceId());
                        return tInNonInvoiceService.insertTInNonInvoiceX(tInNon1006);
                    // "通用机打发票"
                    case "1007":
                        TInNon1007 tInNon1007 = new TInNon1007();
                        BeanUtils.copyProperties(tInCollectNonInvoice, tInNon1007);
                        BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInNon1007);
                        tInNon1007.setId(null);
                        tInNon1007.setInvoiceId(tInNonInvoice.getInvoiceId());
                        return tInNonInvoiceService.insertTInNonInvoiceX(tInNon1007);
                    // "过路费发票"
                    case "1008":
                        TInNon1008 tInNon1008 = new TInNon1008();
                        BeanUtils.copyProperties(tInCollectNonInvoice, tInNon1008);
                        BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInNon1008);
                        tInNon1008.setId(null);
                        tInNon1008.setInvoiceId(tInNonInvoice.getInvoiceId());
                        return tInNonInvoiceService.insertTInNonInvoiceX(tInNon1008);
                    // "区块链电子发票"
                    case "1009":
                        TInNon1009 tInNon1009 = new TInNon1009();
                        BeanUtils.copyProperties(tInCollectNonInvoice, tInNon1009);
                        BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInNon1009);
                        tInNon1009.setId(null);
                        tInNon1009.setInvoiceId(tInNonInvoice.getInvoiceId());
                        return tInNonInvoiceService.insertTInNonInvoiceX(tInNon1009);
                    // "火车票退票费"
                    case "1010":
                        TInNon1010 tInNon1010 = new TInNon1010();
                        BeanUtils.copyProperties(tInCollectNonInvoice, tInNon1010);
                        BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInNon1010);
                        tInNon1010.setId(null);
                        tInNon1010.setInvoiceId(tInNonInvoice.getInvoiceId());
                        return tInNonInvoiceService.insertTInNonInvoiceX(tInNon1010);
//                // "医疗电子票据（住院）"
                    case "1011":
                        TInNon1011 tInNon1011 = new TInNon1011();
                        BeanUtils.copyProperties(tInCollectNonInvoice, tInNon1011);
                        BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInNon1011);
                        tInNon1011.setId(null);
                        tInNon1011.setInvoiceId(tInNonInvoice.getInvoiceId());
                        return tInNonInvoiceService.insertTInNonInvoiceX(tInNon1011);
                   // "医疗电子票据（门诊）"
                    case "1012":
                        TInNon1012 tInNon1012 = new TInNon1012();
                        BeanUtils.copyProperties(tInCollectNonInvoice, tInNon1012);
                        BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInNon1012);
                        tInNon1012.setId(null);
                        tInNon1012.setInvoiceId(tInNonInvoice.getInvoiceId());
                        return tInNonInvoiceService.insertTInNonInvoiceX(tInNon1012);
                   // "通用（电子）发票"
                    case "1013":
                        TInNon1013 tInNon1013 = new TInNon1013();
                        BeanUtils.copyProperties(tInCollectNonInvoice, tInNon1013);
                        BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInNon1013);
                        tInNon1013.setId(null);
                        tInNon1013.setInvoiceId(tInNonInvoice.getInvoiceId());
                        return tInNonInvoiceService.insertTInNonInvoiceX(tInNon1013);
                   // "通用（电子）发票"
                    case "1016":
                        TInNon1016 tInNon1016 = new TInNon1016();
                        BeanUtils.copyProperties(tInCollectNonInvoice, tInNon1016);
                        BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInNon1016);
                        // 明细
                        List<TInNon1016Entry> tInNon1016EntryList = new ArrayList<>();
                        List<ImageInvoicesRecogcollectBizInvoiceTravel> imageInvoicesRecogcollectBizInvoiceTravelList = imageInvoicesRecogcollectMediaInvoice.getInvoiceTravelList();
                        for(ImageInvoicesRecogcollectBizInvoiceTravel travel : imageInvoicesRecogcollectBizInvoiceTravelList){
                            TInNon1016Entry tInNon1016Entry = new TInNon1016Entry();
                            BeanUtils.copyProperties(travel, tInNon1016Entry);
                            tInNon1016Entry.setId(null);
                            tInNon1016EntryList.add(tInNon1016Entry);
                        }
                        tInNon1016.setTInNon1016EntryList(tInNon1016EntryList);
                        tInNon1016.setId(null);
                        tInNon1016.setInvoiceId(tInNonInvoice.getInvoiceId());
                        return tInNonInvoiceService.insertTInNonInvoiceX(tInNon1016);
                    // "其他发票"
                    case "99":
                        TInNon99 tInNon99 = new TInNon99();
                        BeanUtils.copyProperties(tInCollectNonInvoice, tInNon99);
                        BeanUtils.copyProperties(imageInvoicesRecogcollectMediaInvoice, tInNon99);
                        tInNon99.setId(null);
                        tInNon99.setInvoiceId(tInNonInvoice.getInvoiceId());
                        return tInNonInvoiceService.insertTInNonInvoiceX(tInNon99);
                    default:
                        return 0;
                }
            } else {
                return 0;
            }
        }
        return 0;
    }


}
